package org.micode.common.annotation;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * @author wutianbin
 */
@Slf4j
public class EnumValidator implements
        ConstraintValidator<EnumConstraint, Integer> {


    private Class<? extends Enum<?>> enumClass;
    private String field;

    @Override
    public void initialize(EnumConstraint arg0) {
        this.enumClass = arg0.enumClass();
        this.field = arg0.field();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        try {
            Object[] objs = enumClass.getEnumConstants();
            Method code = enumClass.getDeclaredMethod("get" +
                    firstToUpperCase(field));

            for (Object obj : objs) {
                Integer val = (Integer) code.invoke(obj);
                if (value.equals(val)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("Error: ", e);
        }

        return false;
    }

    public String firstToUpperCase(String value) {
        char[] ch = value.toCharArray();

        ch[0] = toUpperChar(ch[0]);

        return new String(ch);
    }

    public char toUpperChar(char c) {
        if(c >= 'a' && c <= 'z') {
            return (char)(c - 32);
        } else {
            return c;
        }
    }

}
